package busca.tesoros.uclm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;


public class RegistrarseActivity extends Activity implements OnClickListener{
	public static final String SERVERIP = "192.168.1.6";
	public static final int SERVERPORT = 8080;
	
	 @Override
	    public void onCreate(Bundle savedInstanceState)
	    {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.registrarse);
	        
	        View ButtonContinue = findViewById(R.id.Enviar);
	        ButtonContinue.setOnClickListener(registrarUsuario);   
	    
	}
	 
	 
	 protected void onDestroy() {
	    	super.onDestroy();
	    }
	    
	    private OnClickListener registrarUsuario = new OnClickListener() {	

	    	public void onClick(View v)  {
	
	switch (v.getId()) {
	case R.id.Enviar:	
	

    	final EditText usuario = (EditText) findViewById(R.id.editUser);
    	final EditText clave = (EditText) findViewById(R.id.editPass);
    	final EditText clave2 = (EditText) findViewById(R.id.editPass2);
    	final EditText mail = (EditText) findViewById(R.id.editEmail);
            final String nombre = usuario.getText().toString();
            final String pass = clave.getText().toString();
            final String pass2 = clave2.getText().toString();
            final String correo = mail.getText().toString();
            
            if(nombre.equals(""))
            {
            	mostrar("nombre");
            }            
            else if((!pass.equals(pass2)) || pass.equals(""))
            {
            	mostrar("pass");
            }
            else if(!isEmail(correo))
            {
            	mostrar("correo");
            }
            else
            {
            	new AsyncTask<Void, Void, String>() {
            		
            		@Override
            		protected String doInBackground(Void... arg0) {
            			Log.i("Client", "trasmitimos los datos del nuevo usuario");
            		   return serverDialog("{ operacion:registro, usuario:"+nombre+", pass:"+pass+", correo:"+correo+"}");
            		      		    
            		}
            		@Override
            		protected void onPostExecute(String inTxt) {
            		    try
            		    {
            		    		JSONObject inJson = new JSONObject(inTxt);
            		    		String response= inJson.getString("response");
            		    		
            		    		if(response.equals("true"))

            		    	        mostrar("true");

            		    		else
            		    			 mostrar("false");
            		    			
           		    
            		    }
            		    catch (Exception ex)
            		    {
            		    	Log.e("Client","JSON Error: " + ex.getMessage());
            		    }        			
            		}
            	}.execute();	

            }
	
	
}

}
	    };
	    
	    private void mostrar(String cadena)
	    {
	    	if(cadena.equals("nombre"))
            {
            	Toast brindis = Toast.makeText(this, "Usuario Obligatorio", 3000); 
        		  brindis.setGravity (Gravity.TOP, -30, 50); 
        		  brindis.show ();
            }            
            else if(cadena.equals("pass"))
            {
            	Toast brindis = Toast.makeText (this, "Las claves no coinciden", 3000); 
      		  brindis.setGravity (Gravity.TOP, -30, 50); 
      		  brindis.show ();
            }
            else if(cadena.equals("correo"))
            {
            	Toast brindis = Toast.makeText (this, "Correo no valido", 3000); 
        		  brindis.setGravity (Gravity.TOP, -30, 50); 
        		  brindis.show ();
            }
            else if(cadena.equals("true"))
            {

                //Volvemos a la pantalla login
                Intent i = new Intent(this, LoginActivity.class);
        		startActivity(i);
        		Toast brindis = Toast.makeText (this, "Registro Realizado", 3000); 
        		  brindis.setGravity (Gravity.TOP, -30, 50); 
        		  brindis.show ();
            }
            else if(cadena.equals("false"))
            		{
            	Toast brindis = Toast.makeText (this, "Error en el registro", 3000); 
      		  brindis.setGravity (Gravity.TOP, -30, 50); 
      		  brindis.show ();
            	
            		}
	    	
	    }

public boolean isEmail(String correo) {
    Pattern pat = null;
    Matcher mat = null;
    pat = Pattern.compile("^([0-9a-zA-Z]([_.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$");
    mat = pat.matcher(correo);
    if (mat.find()) {
        return true;
    }else{
        return false;
    }
}

private String serverDialog(String outTxt)
{
	String inTxt = "";
	try {
		Log.i("Client", "Conectting to "+ SERVERIP + ":" + SERVERPORT);
		InetAddress serverAddr = InetAddress.getByName(SERVERIP);
		Socket clientSocket = new Socket(serverAddr, SERVERPORT);
		
		if(clientSocket.isConnected()) {
			
			PrintWriter out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(clientSocket
					.getOutputStream())), true);

			out.println(outTxt);

			BufferedReader in = new BufferedReader(
					new InputStreamReader(clientSocket.getInputStream()),1024);

			        			
			Log.i("Client", "Response from server:\n");
			String line;
			while ((line = in.readLine()) != null) {
				Log.i("Client", line);
				inTxt += line;
			}
			Log.i("Client", "-----------------\n");
		}
		clientSocket.close();
	}
	catch (Exception e) {
		Log.e("Client", "Error connecting to the library server.", e);
	}
	return inTxt;
}

public void onClick(View v) {
	// TODO Auto-generated method stub
	
}


//
//   Control Menu
//
private static final int MNU_OPC1 = 1;
private static final int MNU_OPC2 = 2;
private static final int MNU_OPC3 = 3;

private static final int SMNU_OPC1 = 31;
private static final int SMNU_OPC2 = 32;
Boolean star=false;
private TextView lblMensaje;
MediaPlayer mp;
			
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
	Intent qr;
	
    switch (item.getItemId()) {
    
        case R.id.menuimagen:
        	qr = new Intent(this,MostrarQRActivity.class);
      		startActivity(qr);		             
      		 return true;
      		               
        case R.id.menusalir:
        	qr = new Intent(this, FinActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        	startActivity(qr);
        	finish();
        	 return true;
        	 
        case R.id.menusonido:
        	if(star)
        	{
        	mp.stop();
        	star=false;
        	}
        	else
        	{		            		
                mp = MediaPlayer.create(this, R.raw.melodia_de_fondo);
            	mp.setLooping(true);
        		mp.start();
        		star=true;
        	}
        	return true;
	default:
            return super.onOptionsItemSelected(item);
    }
}
}
